package com.gws.ievent.scheduler.timewheel;

import lombok.Data;
import org.jctools.queues.MpscUnboundedArrayQueue;

import java.util.Queue;

/**
 * @author song
 * @date 2022/10/26 12:30
 */
@Data
public class Seat {

    private Queue<Bucket> enqueue = new MpscUnboundedArrayQueue<>(64);
    private Bucket head;
    private Bucket tail;


    /**
     * 转移队列中的数据到链表中
     *
     * @param i
     * @return 返回是否全部转移完成
     */
    public boolean transformEnqueueToLink(int i) {
        for (int j = 0; j < i; ++j) {
            Bucket poll = this.enqueue.poll();
            if (poll == null) {
                return true;
            }

            this.add(poll);
        }

        return true;
    }


    /**
     * 添加
     *
     * @param bucket
     */
    public void add(Bucket bucket) {
        if (this.head == null) {
            this.head = bucket;
            this.tail = null;
            return;
        }

        if (this.tail == null) {
            this.head.next = bucket;
            bucket.prev = this.head;
            this.tail = bucket;
            return;
        }

        this.tail.next = bucket;
        bucket.prev = this.tail;
        this.tail = bucket;
    }


    /**
     * 移除
     *
     * @param bucket
     */
    public void remove(Bucket bucket) {
        Bucket prev = bucket.prev;
        Bucket next = bucket.next;

        if (prev != null) {
            prev.next = next;
        }

        if (next != null) {
            next.prev = prev;
        }

        if (bucket == head) {
            this.head = next;
        }

        if (bucket == tail) {
            this.tail = prev;
        }

        bucket.prev = null;
        bucket.next = null;
        bucket.task = null;
    }

}
